"use client";
import { useSession } from "next-auth/react";
import { useEffect, useState } from "react";
import { useParams } from "next/navigation";
import { Card } from "@/components/ui/card";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { toast } from "sonner";
import { Skeleton } from "@/components/ui/skeleton";
import {
  Dialog,
  DialogTrigger,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
} from "@/components/ui/dialog";
import { Textarea } from "@/components/ui/textarea";
import { Button } from "@/components/ui/button";
import { MessageSquare } from "lucide-react";

interface StudentScore {
  student_id: string;
  name: string;
  class_name: string;
  course_name: string;
  score: number;
  gpa: number | null;
  credit: number;
  academic_year: string;
  semester: string;
  credit_gpa: number;
  course_nature: string;
  course_code: string;
}

interface StudentStat {
  student_id: string;
  course_count: number;
  total_credit: number;
  total_credit_gpa: number;
  avg_gpa: number;
  gpa_rank: number;
}

interface Feedback {
  id: string;
  content: string;
  created_at: string;
  status: number;
}

export default function StudentScoresPage() {
  const params = useParams();
  const { data: session, status } = useSession();
  const student_id =
    typeof params?.student_id === "string" ? params.student_id : "";

  const [scores, setScores] = useState<StudentScore[]>([]);
  const [stat, setStat] = useState<StudentStat | null>(null);
  const [loading, setLoading] = useState(true);

  const [feedbackOpen, setFeedbackOpen] = useState(false);
  const [feedbackContent, setFeedbackContent] = useState("");
  const [myFeedbacks, setMyFeedbacks] = useState<Feedback[]>([]);

  const fetchScores = async () => {
    try {
      const res = await fetch(`/api/gpa/detail/${student_id}`);
      if (!res.ok) throw new Error("查询失败");
      const data = await res.json();
      if (data["code"] === -1) throw new Error("查询失败");
      setScores(data);
    } catch (err) {
      console.log(err);
      toast.error("获取成绩失败，请稍后重试");
    } finally {
      setLoading(false);
    }
  };

  const fetchStudentStat = async () => {
    const res = await fetch(`/api/gpa/by-sid?student_id=${student_id}`);
    const data = await res.json();
    setStat(data);
  };

  const fetchMyFeedbacks = async () => {
    const res = await fetch(`/api/feedback/student/${student_id}`);
    const data = await res.json();
    setMyFeedbacks(data);
  };

  const handleSubmitFeedback = async () => {
    if (!feedbackContent.trim()) {
      toast.error("反馈内容不能为空");
      return;
    }

    const res = await fetch(`/api/feedback/create`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ student_id, content: feedbackContent }),
    });

    if (res.ok) {
      toast.success("反馈已提交");
      setFeedbackContent("");
      fetchMyFeedbacks();
    } else {
      toast.error("反馈提交失败");
    }
  };

  useEffect(() => {
    if (student_id) {
      fetchScores();
      fetchStudentStat();
    }
  }, [student_id]);

  useEffect(() => {
    if (student_id && feedbackOpen) {
      fetchMyFeedbacks();
    }
  }, [feedbackOpen, student_id]);

  return (
    <div className="max-w-6xl mx-auto p-6 space-y-6">
      <Card className="p-4 border shadow-md border-gray-200 rounded-md">
        {loading ? (
          <Skeleton className="w-full h-32" />
        ) : scores.length === 0 ? (
          <p className="text-gray-500">未找到该学生的成绩记录。</p>
        ) : (
          <>
            <div className="text-md font-semibold mb-2 text-center">
              学号：{scores[0].student_id} ｜ 姓名：{scores[0].name} ｜ 班级：
              {scores[0].class_name}
            </div>

            <div className="text-sm text-muted-foreground mb-2 text-center">
              课程总数：{stat?.course_count} ｜ 总学分：
              {stat?.total_credit} ｜ 总学分绩点：
              {stat?.total_credit_gpa.toFixed(2)} ｜ 平均绩点：
              {stat?.avg_gpa.toFixed(8)} ｜ 排名：{stat?.gpa_rank}
            </div>

            <div className="text-sm text-muted-foreground mb-2 text-center">
              注意：中期退课不会显示，其他重修记录也会显示，多次课程绩点记录只算最低的绩点。
            </div>

            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>序号</TableHead>
                  <TableHead>课程名称</TableHead>
                  <TableHead>课程号</TableHead>
                  <TableHead>学年</TableHead>
                  <TableHead>学期</TableHead>
                  <TableHead>学分</TableHead>
                  <TableHead>成绩</TableHead>
                  <TableHead>绩点</TableHead>
                  <TableHead>课程性质</TableHead>
                  <TableHead>学分绩点</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {scores.map((score, idx) => (
                  <TableRow key={idx}>
                    <TableCell>{idx + 1}</TableCell>
                    <TableCell>{score.course_name}</TableCell>
                    <TableCell>{score.course_code}</TableCell>
                    <TableCell>{score.academic_year}</TableCell>
                    <TableCell>{score.semester}</TableCell>
                    <TableCell>{score.credit}</TableCell>
                    <TableCell>{score.score}</TableCell>
                    <TableCell>{score.gpa ?? "-"}</TableCell>
                    <TableCell>{score.course_nature}</TableCell>
                    <TableCell>{score.credit_gpa.toFixed(2)}</TableCell>
                  </TableRow>
                ))}
              </TableBody>
            </Table>
          </>
        )}
      </Card>

      {/* 悬浮反馈按钮 + Dialog */}

      {status === "authenticated" && session?.user?.role === "student" && (
        <Dialog open={feedbackOpen} onOpenChange={setFeedbackOpen}>
          <DialogTrigger asChild>
            <Button
              className="fixed bottom-6 right-6 z-50 shadow-lg rounded-full px-6 py-3"
              variant="default"
            >
              <MessageSquare className="mr-2 w-4 h-4" />
              反馈
            </Button>
          </DialogTrigger>
          <DialogContent className="max-w-2xl">
            <DialogHeader>
              <DialogTitle>提交反馈</DialogTitle>
            </DialogHeader>

            {/* 上半部分：反馈提交 */}
            <div className="space-y-2">
              <Textarea
                placeholder="请输入反馈内容"
                value={feedbackContent}
                onChange={(e) => setFeedbackContent(e.target.value)}
                rows={4}
              />
              <DialogFooter>
                <Button onClick={handleSubmitFeedback}>提交反馈</Button>
              </DialogFooter>
            </div>

            {/* 下半部分：历史反馈 */}
            <div className="mt-6 border-t pt-4 space-y-2 max-h-60 overflow-y-auto">
              <h3 className="text-sm font-medium text-muted-foreground mb-2">
                我的反馈记录
              </h3>
              {myFeedbacks.length === 0 ? (
                <p className="text-sm text-gray-500">暂无反馈记录</p>
              ) : (
                myFeedbacks.map((fb) => (
                  <div
                    key={fb.id}
                    className="text-sm text-gray-700 border rounded p-2"
                  >
                    <div className="mb-1">内容：{fb.content}</div>
                    <div className="text-xs text-gray-500">
                      时间：{new Date(fb.created_at).toLocaleString()} ｜ 状态：
                      {fb.status === 0 ? "未处理" : "已处理"}
                    </div>
                  </div>
                ))
              )}
            </div>
          </DialogContent>
        </Dialog>
      )}
    </div>
  );
}
